package com.ayoka.ui.customer_service;

import android.animation.ObjectAnimator;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.v7.widget.LinearLayoutManager;
import android.view.MotionEvent;
import android.view.View;
import android.widget.AbsListView;
import android.widget.ListView;
import android.widget.Toast;

import com.ayoka.Constant;
import com.ayoka.R;
import com.ayoka.adapter.CustomerServiceMessageOptionAdapter;
import com.ayoka.base.BaseActivity;
import com.ayoka.bean.UserInformation;
import com.ayoka.databinding.ActivityCustomerServiceBinding;
import com.ayoka.mvp.CustomerServiceMVP;
import com.ayoka.mvp.CustomerServiceMVP.CustomerServicePresenter;
import com.ayoka.mvp.CustomerServiceMVP.ICustomerServiceView;
import com.ayoka.mvp.CustomerServiceMVP.CustomerServiceModel.MessageOptionBean;
import com.jcp.baselibrary.brvah.BaseQuickAdapter;
import com.jcp.baselibrary.model.ToolBarOptions;
import com.jcp.baselibrary.utils.SPUtil;
import com.jcp.baselibrary.utils.UIUtils;
import com.jincp.image.load.ImageLoaderOptions;
import com.jincp.image.load.ImageLoaderProxy;
import com.tencent.TIMConversationType;
import com.tencent.TIMCustomElem;
import com.tencent.TIMMessage;
import com.tencent.TIMMessageDraft;
import com.tencent.TIMMessageLocator;
import com.tencent.TIMMessageStatus;
import com.tencent.TIMTextElem;
import com.tencent.timsdk.adapter.ChatAdapter;
import com.tencent.timsdk.emotion.EmotionChatInput;
import com.tencent.timsdk.interf.ChatView;
import com.tencent.timsdk.model.CustomMessage;
import com.tencent.timsdk.model.FileMessage;
import com.tencent.timsdk.model.ImageMessage;
import com.tencent.timsdk.model.Message;
import com.tencent.timsdk.model.MessageFactory;
import com.tencent.timsdk.model.TextMessage;
import com.tencent.timsdk.model.VideoMessage;
import com.tencent.timsdk.model.VoiceMessage;
import com.tencent.timsdk.ui.ImagePreviewActivity;
import com.tencent.timsdk.util.FileUtil;
import com.tencent.timsdk.util.MediaUtil;
import com.tencent.timsdk.util.RecorderUtil;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by admin on 2017/3/22.
 */

public class CustomerServiceActivity extends BaseActivity<ActivityCustomerServiceBinding, CustomerServicePresenter> implements ChatView, ICustomerServiceView {

    private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100;
    private static final int IMAGE_STORE = 200;
    private static final int FILE_CODE = 300;
    private static final int IMAGE_PREVIEW = 400;

    public static void start(Activity activity) {
        Intent intent = new Intent(activity, CustomerServiceActivity.class);
        activity.startActivity(intent);
    }

    private List<Message> messageList = new ArrayList<>();
    private ChatAdapter adapter;
    private Uri fileUri;

    private String identify = "ayoka_service";
    private TIMConversationType type = TIMConversationType.C2C;

    private RecorderUtil recorder = new RecorderUtil();

    private ObjectAnimator mAnimator;
    private CustomerServiceMessageOptionAdapter customerServiceMessageOptionAdapter;

    @Override
    public int getContentLayout() {
        return R.layout.activity_customer_service;
    }

    @Override
    public void initViews() {
        // 设置关联的chatView
        mDataBinding.inputPanel.setChatView(this);
        mDataBinding.inputPanel.setContent(mDataBinding.list);
        // 设置listView
        adapter = new ChatAdapter(this, R.layout.item_message, messageList, new ChatAdapter.ChatAdapterLayoutCallback() {
            @Override
            public void configChatAdapterLayout(Message message, ChatAdapter.ViewHolder viewHolder) {
                ImageLoaderProxy.getInstance().displayImage(R.mipmap.icon_ayoka_logo, viewHolder.leftAvatar, ImageLoaderOptions.getCircleOptions());
                ImageLoaderProxy.getInstance().displayImage(UserInformation.getInstance().user_info.LocalAvatar, viewHolder.rightAvatar, ImageLoaderOptions.getCircleOptions());
            }
        });
        mDataBinding.list.setAdapter(adapter);
        mDataBinding.list.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        mDataBinding.inputPanel.setInputMode(EmotionChatInput.InputMode.NONE);
                        break;
                }
                return false;
            }
        });
        mDataBinding.list.setOnScrollListener(new AbsListView.OnScrollListener() {

            private int firstItem;

            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {
                if (scrollState == AbsListView.OnScrollListener.SCROLL_STATE_IDLE && firstItem == 0) {
                    //如果拉到顶端读取更多消息
                    mPresenter.getMessage(messageList.size() > 0 ? messageList.get(0).getMessage() : null);

                }
            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
                firstItem = firstVisibleItem;
            }
        });
    }


    @Override
    protected void initData(Bundle savedInstanceState) {
        ToolBarOptions options = new ToolBarOptions("智能客服");
        setCustomToolBar(mDataBinding.customToolbar.toolbar, options);
        mPresenter.start();
        //设置动画
        mAnimator = ObjectAnimator.ofFloat(mDataBinding.recyclerView, "translationX", 0);
    }

    @Override
    protected CustomerServicePresenter getPresenter() {
        return new CustomerServiceMVP.CustomerServicePresenter(this, identify, type);
    }

    /**
     * 显示消息
     *
     * @param message
     */
    @Override
    public void showMessage(TIMMessage message) {
        if (message == null) {
            adapter.notifyDataSetChanged();
        } else {
            Message mMessage = MessageFactory.getMessage(message);
            if (mMessage != null) {
                if (mMessage instanceof CustomMessage) {
                    CustomMessage.Type messageType = ((CustomMessage) mMessage).getType();
                    switch (messageType) {
                        case TYPING:
                            ToolBarOptions options = new ToolBarOptions(getString(R.string.chat_typing));
                            setCustomToolBar(mDataBinding.customToolbar.toolbar, options);
                            UIUtils.removeTask(resetTitle);
                            UIUtils.postTaskDelay(resetTitle, 3000);
                            break;
                        default:
                            break;
                    }
                } else {
                    if (messageList.size() == 0) {
                        mMessage.setHasTime(null);
                    } else {
                        mMessage.setHasTime(messageList.get(messageList.size() - 1).getMessage());
                    }
                    messageList.add(mMessage);
                    adapter.notifyDataSetChanged();
                    mDataBinding.list.setSelection(adapter.getCount() - 1);
                }

            }
        }
    }

    @Override
    public void showMessage(List<TIMMessage> messages) {
        int newMsgNum = 0;
        for (int i = 0; i < messages.size(); ++i) {
            Message mMessage = MessageFactory.getMessage(messages.get(i));
            if (mMessage == null || messages.get(i).status() == TIMMessageStatus.HasDeleted)
                continue;
            if (mMessage instanceof CustomMessage && (((CustomMessage) mMessage).getType() == CustomMessage.Type.TYPING ||
                    ((CustomMessage) mMessage).getType() == CustomMessage.Type.INVALID)) continue;
            ++newMsgNum;
            if (i != messages.size() - 1) {
                mMessage.setHasTime(messages.get(i + 1));
                messageList.add(0, mMessage);
            } else {
                mMessage.setHasTime(null);
                messageList.add(0, mMessage);
            }
        }
        adapter.notifyDataSetChanged();
        mDataBinding.list.setSelection(newMsgNum);
    }

    @Override
    public void showRevokeMessage(TIMMessageLocator timMessageLocator) {

    }

    /**
     * 清除所有消息，等待刷新
     */
    @Override
    public void clearAllMessage() {
        messageList.clear();
    }

    /**
     * 发送消息成功
     *
     * @param message 返回的消息
     */
    @Override
    public void onSendMessageSuccess(TIMMessage message) {
        showMessage(message);
    }

    /**
     * 发送消息失败
     *
     * @param code 返回码
     * @param desc 返回描述
     */
    @Override
    public void onSendMessageFail(int code, String desc, TIMMessage message) {
        long id = message.getMsgUniqueId();
        for (Message msg : messageList) {
            if (msg.getMessage().getMsgUniqueId() == id) {
                switch (code) {
                    case 80001:
                        //发送内容包含敏感词
                        msg.setDesc(getString(R.string.chat_content_bad));
                        adapter.notifyDataSetChanged();
                        break;
                }
            }
        }

    }

    /**
     * 发送图片消息
     */
    @Override
    public void sendImage() {
        Intent intent_album = new Intent("android.intent.action.GET_CONTENT");
        intent_album.setType("image/*");
        startActivityForResult(intent_album, IMAGE_STORE);
    }

    /**
     * 发送照片消息
     */
    @Override
    public void sendPhoto() {
        Intent intent_photo = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        if (intent_photo.resolveActivity(getPackageManager()) != null) {
            File tempFile = FileUtil.getTempFile(FileUtil.FileType.IMG);
            if (tempFile != null) {
                fileUri = Uri.fromFile(tempFile);
            }
            intent_photo.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
            startActivityForResult(intent_photo, CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);
        }
    }

    /**
     * 发送文本消息
     */
    @Override
    public void sendText() {
        Message message = new TextMessage(mDataBinding.inputPanel.getText());
        mPresenter.sendMessage(message.getMessage());
        mDataBinding.inputPanel.setText("");
        if (mDataBinding.recyclerView.getX() == 0) {
            // 消失
            mAnimator.setFloatValues(0, mDataBinding.recyclerView.getWidth());
            mAnimator.start();
        }
    }

    /**
     * 发送文件
     */
    @Override
    public void sendFile() {
        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        intent.setType("*/*");
        startActivityForResult(intent, FILE_CODE);
    }

    /**
     * 发送文件
     */
    private void sendFile(String path) {
        if (path == null) return;
        File file = new File(path);
        if (file.exists()) {
            if (file.length() > 1024 * 1024 * 10) {
                Toast.makeText(this, getString(R.string.chat_file_too_large), Toast.LENGTH_SHORT).show();
            } else {
                Message message = new FileMessage(path);
                mPresenter.sendMessage(message.getMessage());
            }
        } else {
            Toast.makeText(this, getString(R.string.chat_file_not_exist), Toast.LENGTH_SHORT).show();
        }

    }


    /**
     * 开始发送语音消息
     */
    @Override
    public void startSendVoice() {
        mDataBinding.voiceSending.setVisibility(View.VISIBLE);
        mDataBinding.voiceSending.showRecording();
        recorder.startRecording();

    }

    /**
     * 结束发送语音消息
     */
    @Override
    public void endSendVoice() {
        mDataBinding.voiceSending.release();
        mDataBinding.voiceSending.setVisibility(View.GONE);
        recorder.stopRecording();
        if (recorder.getTimeInterval() < 1) {
            Toast.makeText(this, getResources().getString(R.string.chat_audio_too_short), Toast.LENGTH_SHORT).show();
        } else {
            Message message = new VoiceMessage(recorder.getTimeInterval(), recorder.getFilePath());
            mPresenter.sendMessage(message.getMessage());
        }
    }

    /**
     * 发送小视频消息
     *
     * @param fileName 文件名
     */
    @Override
    public void sendVideo(String fileName) {
        Message message = new VideoMessage(fileName);
        mPresenter.sendMessage(message.getMessage());
    }


    /**
     * 结束发送语音消息
     */
    @Override
    public void cancelSendVoice() {

    }

    /**
     * 正在发送
     */
    @Override
    public void sending() {
        if (type == TIMConversationType.C2C) {
            Message message = new CustomMessage(CustomMessage.Type.TYPING);
            mPresenter.sendOnlineMessage(message.getMessage());
        }
    }

    /**
     * 显示草稿
     */
    @Override
    public void showDraft(TIMMessageDraft draft) {
        mDataBinding.inputPanel.getText().append(TextMessage.getString(draft.getElems(), this));
    }

    @Override
    public void onRecyclerViewTouch() {

    }

    @Override
    public void onSoftKeyboardShow() {
        mDataBinding.list.smoothScrollToPosition(adapter.getCount() - 1);
    }

    @Override
    public void onTopLoadMore(int lastItemPosition) {

    }

    @Override
    public void showMessageOptions(List<MessageOptionBean> options) {
        if (customerServiceMessageOptionAdapter == null){
            mDataBinding.recyclerView.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false));
            customerServiceMessageOptionAdapter = new CustomerServiceMessageOptionAdapter(options);
            customerServiceMessageOptionAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
                @Override
                public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                    MessageOptionBean optionBean = (MessageOptionBean) adapter.getData().get(position);
                    TIMMessage message = new TIMMessage();
                    TIMTextElem textElem = new TIMTextElem();
                    textElem.setText(optionBean.text);
                    message.addElement(textElem);
                    TIMCustomElem customElem = new TIMCustomElem();
                    customElem.setData(optionBean.value.getBytes());
                    message.addElement(customElem);
                    mPresenter.sendMessage(message);
                    // 消失
                    mAnimator.setFloatValues(0, mDataBinding.recyclerView.getWidth());
                    mAnimator.start();
                }
            });
            mDataBinding.recyclerView.setAdapter(customerServiceMessageOptionAdapter);
        } else {
            customerServiceMessageOptionAdapter.setNewData(options);
        }
        // 显示
        mAnimator.setFloatValues(mDataBinding.recyclerView.getWidth(), 0);
        mAnimator.start();
    }

    /**
     * 将标题设置为对象名称
     */
    private Runnable resetTitle = new Runnable() {
        @Override
        public void run() {
            ToolBarOptions options = new ToolBarOptions("智能客服");
            setCustomToolBar(mDataBinding.customToolbar.toolbar, options);
        }
    };

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) {
            if (resultCode == RESULT_OK && fileUri != null) {
                showImagePreview(fileUri.getPath());
            }
        } else if (requestCode == IMAGE_STORE) {
            if (resultCode == RESULT_OK && data != null) {
                showImagePreview(FileUtil.getFilePath(this, data.getData()));
            }

        } else if (requestCode == FILE_CODE) {
            if (resultCode == RESULT_OK) {
                sendFile(FileUtil.getFilePath(this, data.getData()));
            }
        } else if (requestCode == IMAGE_PREVIEW) {
            if (resultCode == RESULT_OK) {
                boolean isOri = data.getBooleanExtra("isOri", false);
                String path = data.getStringExtra("path");
                File file = new File(path);
                if (file.exists() && file.length() > 0) {
                    if (file.length() > 1024 * 1024 * 10) {
                        Toast.makeText(this, getString(R.string.chat_file_too_large), Toast.LENGTH_SHORT).show();
                    } else {
                        Message message = new ImageMessage(path, isOri);
                        mPresenter.sendMessage(message.getMessage());
                    }
                } else {
                    Toast.makeText(this, getString(R.string.chat_file_not_exist), Toast.LENGTH_SHORT).show();
                }
            }
        }

    }

    private void showImagePreview(String path) {
        if (path == null) return;
        Intent intent = new Intent(this, ImagePreviewActivity.class);
        intent.putExtra("path", path);
        startActivityForResult(intent, IMAGE_PREVIEW);
    }

    @Override
    public void onPause() {
        super.onPause();
        //退出聊天界面时输入框有内容，保存草稿
        if (mDataBinding.inputPanel.getText().length() > 0) {
            TextMessage message = new TextMessage(mDataBinding.inputPanel.getText());
            mPresenter.saveDraft(message.getMessage());
        } else {
            mPresenter.saveDraft(null);
        }
        mPresenter.readMessages();
        MediaUtil.getInstance().stop();
    }

    @Override
    public void onDestroy() {
        SPUtil.putLong(Constant.QUIT_AI_MILLS, System.currentTimeMillis());
        super.onDestroy();
    }
}
